/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
  public:
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode* res =  reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return res;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if(head1 == NULL) return head2;
        if(head2 == NULL) return head1;
        head1 = reverseList(head1), head2 = reverseList(head2);
        ListNode* res = new ListNode(-1);   // 结果头节点
        ListNode* cur = res;
        int carry = 0;  // 进位
        while (head1 || head2) {
            int sum = carry;
            if(head1){
                sum += head1->val;
                head1 = head1->next;
            }
            if(head2){
                sum += head2->val;
                head2 = head2->next;
            }
            carry = sum / 10;
            cur->next = new ListNode(sum % 10);
            cur = cur->next;
        }
        if(carry != 0) cur->next = new ListNode(carry);
        return reverseList(res->next);
    }
};